package com.doform.android.xianggucheng.activity.login;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseTitleActivity;
import com.doform.android.xianggucheng.activity.MainActivity;
import com.doform.android.xianggucheng.bean.IPickerAddressBean;
import com.doform.android.xianggucheng.bean.LoginBean;
import com.doform.android.xianggucheng.bean.RegisterBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqLoginBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqRegister3;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.GetJsonDataUtil;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-07-27.
 * GitHub：https://github.com/cxydxpx
 */

public class RegisterActivity3 extends BaseTitleActivity {

    @BindView(R.id.et_company)
    EditText et_company;

    @BindView(R.id.et_person)
    EditText et_person;

    @BindView(R.id.tv_address)
    TextView tv_address;

    @BindView(R.id.et_detail_address)
    EditText et_detail_address;

    @BindView(R.id.et_password)
    EditText et_password;

    @BindView(R.id.et_password2)
    EditText et_password2;
    private String phone;

    @Override
    protected int layoutResId() {
        return R.layout.activity_register3;
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("注册");
    }

    @Override
    protected void init() {
        super.init();
        this.phone = getIntent().getStringExtra(Constans.EXTRA_REGISTER_PHONE2);
    }

    @Override
    protected void initData() {
        super.initData();
        initDateData();
    }

    @OnClick({R.id.btn_next, R.id.tv_address})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                beforeSubmit();
                break;
            case R.id.tv_address:
                showAddress();
                break;
            default:
                break;
        }
    }

    private void beforeSubmit() {
        String mCompany = et_company.getText().toString().trim();
        String mPerson = et_person.getText().toString().trim();
        String mDetail_address = et_detail_address.getText().toString().trim();
        String mPassword = et_password.getText().toString().trim();
        String mPassword2 = et_password2.getText().toString().trim();

        if (TextUtils.isEmpty(mCompany)) {
            TsUtils.showToast("请输入单位名称");
            return;
        } else if (TextUtils.isEmpty(mPerson)) {
            TsUtils.showToast("请输入联系人");
            return;
        } else if (TextUtils.isEmpty(mZoneName)) {
            TsUtils.showToast("请输入所在地区");
            return;
        } else if (TextUtils.isEmpty(mDetail_address)) {
            TsUtils.showToast("请输入详细地址");
            return;
        } else if (TextUtils.isEmpty(mPassword)) {
            TsUtils.showToast("请输入密码");
            return;
        } else if (TextUtils.isEmpty(mPassword2)) {
            TsUtils.showToast("请再次输入密码");
            return;
        } else if (!mPassword.equals(mPassword2)) {
            TsUtils.showToast("密码不一致");
            return;
        }

        postDataToService(mCompany, mPerson, phone, mPassword, mProvinceId, mProvinceName, mCityId, mCityName, mZoneId, mZoneName);
    }

    /**
     * 注册
     *
     * @param mCompany
     * @param mPerson
     * @param phone
     * @param mPassword
     * @param mProvinceId
     * @param mProvinceName
     * @param mCityId
     * @param mCityName
     * @param mZoneId
     * @param mZoneName
     */
    private void postDataToService(String mCompany, String mPerson, String phone, String mPassword,
                                   String mProvinceId, String mProvinceName, String mCityId, String mCityName,
                                   String mZoneId, String mZoneName) {
        HttpManager.instance()
                .register(new ReqRegister3(mCompany, mPerson, phone, mPassword, mProvinceId, mProvinceName, mCityId, mCityName, mZoneId, mZoneName))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Function<RegisterBean, ObservableSource<LoginBean>>() {
                             @Override
                             public ObservableSource<LoginBean> apply(@NonNull RegisterBean registerBean) throws Exception {
                                 return login(registerBean);
                             }
                         }
                ).subscribe(new ErrorHandleSubscriber<LoginBean>() {
                                @Override
                                public void onNext(@NonNull LoginBean loginBean) {
                                    startActivity(new Intent(RegisterActivity3.this, MainActivity.class));
                                    finish();
                                }
                            }
        )
        ;
    }

    private Observable<LoginBean> login(RegisterBean loginBean) {
        return HttpManager
                .instance()
                .login(new ReqLoginBean(loginBean.getUsername(), loginBean.getPassword()));
    }


    private String mCityId;
    private String mZoneId;
    private String mCityName;
    private String mZoneName;
    private String mProvinceId;
    private String mProvinceName;


    private void showAddress() {

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                mProvinceName = options1Items.get(options1).getPickerViewText();
                mProvinceId = String.valueOf(options1Items.get(options1).getId());

                mCityName = options2Items.get(options1).get(options2).getPickerViewText();
                mCityId = String.valueOf(options2Items.get(options1).get(options2).getCode());

                mZoneName = options3Items.get(options1).get(options2).get(options3).getPickerViewText();
                mZoneId = String.valueOf(options3Items.get(options1).get(options2).get(options3).getCode());

                tv_address.setText(options1Items.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2).getPickerViewText() + "-" +
                        options3Items.get(options1).get(options2).get(options3).getPickerViewText());

            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }

    private ArrayList<IPickerAddressBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<IPickerAddressBean.CityBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<IPickerAddressBean.CityBean.ZoneBean>>> options3Items = new ArrayList<>();

    private void initDateData() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                /**
                 * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
                 * 关键逻辑在于循环体
                 *
                 * */
                String JsonData = new GetJsonDataUtil().getJson(RegisterActivity3.this, "province.json");//获取assets目录下的json文件数据

                ArrayList<IPickerAddressBean> jsonBean = parseData(JsonData);//用Gson 转成实体

                /**
                 * 添加省份数据
                 * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
                 * PickerView会通过getPickerViewText方法获取字符串显示出来。
                 */
                options1Items = jsonBean;

                for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
                    ArrayList<IPickerAddressBean.CityBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
                    ArrayList<ArrayList<IPickerAddressBean.CityBean.ZoneBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

                    for (int c = 0; c < jsonBean.get(i).getCity().size(); c++) {//遍历该省份的所有城市
                        IPickerAddressBean.CityBean cityBean = jsonBean.get(i).getCity().get(c);
                        CityList.add(cityBean);//添加城市

                        ArrayList<IPickerAddressBean.CityBean.ZoneBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                        //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                        if (jsonBean.get(i).getCity().get(c).getZone() == null
                                || jsonBean.get(i).getCity().get(c).getZone().size() == 0) {
                            City_AreaList.add(new IPickerAddressBean.CityBean.ZoneBean());
                        } else {
                            for (int d = 0; d < jsonBean.get(i).getCity().get(c).getZone().size(); d++) {//该城市对应地区所有数据
                                IPickerAddressBean.CityBean.ZoneBean AreaName = jsonBean.get(i).getCity().get(c).getZone().get(d);

                                City_AreaList.add(AreaName);//添加该城市所有地区数据
                            }
                        }
                        Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                    }
                    /**
                     * 添加城市数据
                     */
                    options2Items.add(CityList);
                    /**
                     * 添加地区数据
                     */
                    options3Items.add(Province_AreaList);

                }
            }
        }.start();
    }

    public ArrayList<IPickerAddressBean> parseData(String result) {//Gson 解析
        ArrayList<IPickerAddressBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                IPickerAddressBean entity = gson.fromJson(data.optJSONObject(i).toString(), IPickerAddressBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }


}
